package com.wechat.ferry.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wechat.ferry.entity.dto.HotNewsDTO;
import com.wechat.ferry.service.RobotService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Chuan.Chen
 * @Version 1.0.0
 * @Description
 * @CreateTime 2025/6/27 10:03
 */
@Service
@Slf4j
public class RobotServiceImpl implements RobotService {


    @Override
    public String getZhHotData() throws Exception {
        List<HotNewsDTO> hotList = Lists.newArrayList();
        zhHot(hotList);
        if (CollUtil.isNotEmpty(hotList)) {
            StringBuilder sb = new StringBuilder();
            sb.append("\uD83D\uDD25【全网热榜速递】一键掌握各大平台热搜TOP10！\uD83D\uDD0D\n");
            sb.append("\uD83D\uDCE2【今日全网热榜】更多平台热榜详情\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            sb.append("包含抖音/知乎/虎扑/财联社/华尔街见闻/微博/今日头条等权威平台实时热榜\n");
            sb.append("\n");
            Map<String, List<HotNewsDTO>> hotMap = hotList.stream().collect(Collectors.groupingBy(HotNewsDTO::getTypeKey, HashMap::new, Collectors.toList()));
            hotMap.forEach((k, v) -> {
                switch (k) {
                    case "知乎":
                        sb.append("\uD83E\uDDE0 知乎热榜TOP10\n");
                        break;
                    case "抖音":
                        sb.append("\uD83C\uDFB5 抖音热榜TOP10\n");
                        sb.append("\uD83D\uDD17 温馨提示：手机微信内无法直接打开抖音链接\n");
                        sb.append("⚠\uFE0F请复制链接到浏览器打开，或通过电脑端微信访问\n");
                        break;
                    case "华尔街见闻":
                        sb.append("\uD83D\uDCCA 华尔街见闻热榜TOP10\n");
                        break;
                    case "财联社":
                        sb.append("\uD83D\uDCB0 财联社热榜TOP10\n");
                        break;
                }
                sb.append("\n");
                for (int i = 0; i < v.size(); i++) {
                    HotNewsDTO hotNewsDTO = v.get(i);
                    sb.append(i + 1 + ". " + hotNewsDTO.getTitle() + "\n");
                    sb.append("【" + hotNewsDTO.getUrl() + "】\n");
                    sb.append("\n");
                }
            });
            sb.append("\uD83D\uDCA1 早知天下事，快人一步掌握热点！\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            return sb.toString();
        }
        return null;
    }

    @Override
    public String getDyHotData() throws Exception {
        List<HotNewsDTO> hotList = Lists.newArrayList();
        dyHot(hotList);
        if (CollUtil.isNotEmpty(hotList)) {
            StringBuilder sb = new StringBuilder();
            sb.append("\uD83D\uDD25【全网热榜速递】一键掌握各大平台热搜TOP10！\uD83D\uDD0D\n");
            sb.append("\uD83D\uDCE2【今日全网热榜】更多平台热榜详情\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            sb.append("包含抖音/知乎/虎扑/财联社/华尔街见闻/微博/今日头条等权威平台实时热榜\n");
            sb.append("\n");
            Map<String, List<HotNewsDTO>> hotMap = hotList.stream().collect(Collectors.groupingBy(HotNewsDTO::getTypeKey, HashMap::new, Collectors.toList()));
            hotMap.forEach((k, v) -> {
                switch (k) {
                    case "知乎":
                        sb.append("\uD83E\uDDE0 知乎热榜TOP10\n");
                        break;
                    case "抖音":
                        sb.append("\uD83C\uDFB5 抖音热榜TOP10\n");
                        sb.append("\uD83D\uDD17 温馨提示：手机微信内无法直接打开抖音链接\n");
                        sb.append("⚠\uFE0F请复制链接到浏览器打开，或通过电脑端微信访问\n");
                        break;
                    case "华尔街见闻":
                        sb.append("\uD83D\uDCCA 华尔街见闻热榜TOP10\n");
                        break;
                    case "财联社":
                        sb.append("\uD83D\uDCB0 财联社热榜TOP10\n");
                        break;
                }
                sb.append("\n");
                for (int i = 0; i < v.size(); i++) {
                    HotNewsDTO hotNewsDTO = v.get(i);
                    sb.append(i + 1 + ". " + hotNewsDTO.getTitle() + "\n");
                    sb.append("【" + hotNewsDTO.getUrl() + "】\n");
                    sb.append("\n");
                }
            });
            sb.append("\uD83D\uDCA1 早知天下事，快人一步掌握热点！\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            return sb.toString();
        }
        return null;
    }

    @Override
    public String getHejHotData() throws Exception {
        List<HotNewsDTO> hotList = Lists.newArrayList();
        wallstreetcnHot(hotList);
        if (CollUtil.isNotEmpty(hotList)) {
            StringBuilder sb = new StringBuilder();
            sb.append("\uD83D\uDD25【全网热榜速递】一键掌握各大平台热搜TOP10！\uD83D\uDD0D\n");
            sb.append("\uD83D\uDCE2【今日全网热榜】更多平台热榜详情\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            sb.append("包含抖音/知乎/虎扑/财联社/华尔街见闻/微博/今日头条等权威平台实时热榜\n");
            sb.append("\n");
            Map<String, List<HotNewsDTO>> hotMap = hotList.stream().collect(Collectors.groupingBy(HotNewsDTO::getTypeKey, HashMap::new, Collectors.toList()));
            hotMap.forEach((k, v) -> {
                switch (k) {
                    case "知乎":
                        sb.append("\uD83E\uDDE0 知乎热榜TOP10\n");
                        break;
                    case "抖音":
                        sb.append("\uD83C\uDFB5 抖音热榜TOP10\n");
                        sb.append("\uD83D\uDD17 温馨提示：手机微信内无法直接打开抖音链接\n");
                        sb.append("⚠\uFE0F请复制链接到浏览器打开，或通过电脑端微信访问\n");
                        break;
                    case "华尔街见闻":
                        sb.append("\uD83D\uDCCA 华尔街见闻热榜TOP10\n");
                        break;
                    case "财联社":
                        sb.append("\uD83D\uDCB0 财联社热榜TOP10\n");
                        break;
                }
                sb.append("\n");
                for (int i = 0; i < v.size(); i++) {
                    HotNewsDTO hotNewsDTO = v.get(i);
                    sb.append(i + 1 + ". " + hotNewsDTO.getTitle() + "\n");
                    sb.append("【" + hotNewsDTO.getUrl() + "】\n");
                    sb.append("\n");
                }
            });
            sb.append("\uD83D\uDCA1 早知天下事，快人一步掌握热点！\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            return sb.toString();
        }
        return null;
    }

    @Override
    public String getClsHotData() throws Exception {
        List<HotNewsDTO> hotList = Lists.newArrayList();
        clsHot(hotList);
        if (CollUtil.isNotEmpty(hotList)) {
            StringBuilder sb = new StringBuilder();
            sb.append("\uD83D\uDD25【全网热榜速递】一键掌握各大平台热搜TOP10！\uD83D\uDD0D\n");
            sb.append("\uD83D\uDCE2【今日全网热榜】更多平台热榜详情\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            sb.append("包含抖音/知乎/虎扑/财联社/华尔街见闻/微博/今日头条等权威平台实时热榜\n");
            sb.append("\n");
            Map<String, List<HotNewsDTO>> hotMap = hotList.stream().collect(Collectors.groupingBy(HotNewsDTO::getTypeKey, HashMap::new, Collectors.toList()));
            hotMap.forEach((k, v) -> {
                switch (k) {
                    case "知乎":
                        sb.append("\uD83E\uDDE0 知乎热榜TOP10\n");
                        break;
                    case "抖音":
                        sb.append("\uD83C\uDFB5 抖音热榜TOP10\n");
                        sb.append("\uD83D\uDD17 温馨提示：手机微信内无法直接打开抖音链接\n");
                        sb.append("⚠\uFE0F请复制链接到浏览器打开，或通过电脑端微信访问\n");
                        break;
                    case "华尔街见闻":
                        sb.append("\uD83D\uDCCA 华尔街见闻热榜TOP10\n");
                        break;
                    case "财联社":
                        sb.append("\uD83D\uDCB0 财联社热榜TOP10\n");
                        break;
                }
                sb.append("\n");
                for (int i = 0; i < v.size(); i++) {
                    HotNewsDTO hotNewsDTO = v.get(i);
                    sb.append(i + 1 + ". " + hotNewsDTO.getTitle() + "\n");
                    sb.append("【" + hotNewsDTO.getUrl() + "】\n");
                    sb.append("\n");
                }
            });
            sb.append("\uD83D\uDCA1 早知天下事，快人一步掌握热点！\uD83D\uDC47\n");
            sb.append("【https://news.umeican.com】\n");
            return sb.toString();
        }
        return null;
    }


    /**
     * 知乎
     */
    private void zhHot(List<HotNewsDTO> hotList) throws Exception {
        String url = "https://newsnow.busiyi.world/api/s?id=zhihu&latest";
        setHotData(url, 10, "知乎", "title", "url", hotList);
    }

    /**
     * 华尔街见闻
     */
    private void wallstreetcnHot(List<HotNewsDTO> hotList) throws Exception {
        String url = "https://newsnow.busiyi.world/api/s?id=wallstreetcn-hot&latest";
        setHotData(url, 10, "华尔街见闻", "title", "url", hotList);
    }

    /**
     * 抖音
     */
    private void dyHot(List<HotNewsDTO> hotList) throws Exception {
        String url = "https://newsnow.busiyi.world/api/s?id=douyin&latest";
        setHotData(url, 10, "抖音", "title", "url", hotList);
    }

    /**
     * 财联社
     */
    private void clsHot(List<HotNewsDTO> hotList) throws Exception {
        String url = "https://newsnow.busiyi.world/api/s?id=cls-hot&latest";
        setHotData(url, 10, "财联社", "title", "url", hotList);
    }


    private void setHotData(String url, Integer needSize, String typeKey, String titleKey, String urlKey, List<HotNewsDTO> hotList) throws Exception {
        try {
            Thread.sleep(1000L);
            String cookieStr = "_ga=GA1.1.351043991.1751869310;_ga_EL9HHYE5LC=GS2.1.s1751869309$o1$g0$t1751869309$j60$l0$h";
            String result = HttpRequest.get(url)
//                    .cookie(cookieStr)
//                    .header("Accept","*/*")
//                    .header("Accept-Encoding","gzip, deflate, br, zstd")
//                    .header("Accept-Language","zh-CN,zh;q=0.9")
//                    .header("Cookie","_ga=GA1.1.351043991.1751869310;_ga_EL9HHYE5LC=GS2.1.s1751869309$o1$g0$t1751869309$j60$l0$h")
//                    .header("Priority","u=1, i")
//                    .header("Referer","https://news.umeican.com/")
//                    .header("Sec-Ch-Ua","\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"")
//                    .header("Sec-Ch-Ua-Mobile","?0")
//                    .header("Sec-Ch-Ua-Platform","\"Windows\"")
//                    .header("Sec-Fetch-Dest","empty")
//                    .header("Sec-Fetch-Mode","cors")
//                    .header("Sec-Fetch-Site","same-origin")
//                    .header("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36")
                    .timeout(20000).execute().body();
            if (ObjectUtil.isNotEmpty(result)) {
                // 解析为JsonObject
                JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
                // 获取数组
                JsonArray carsArray = jsonObject.getAsJsonArray("items");
                for (int i = 0; i < (carsArray.size() >= needSize ? needSize : carsArray.size()); i++) {
                    JsonObject itemJson = carsArray.get(i).getAsJsonObject();
                    String hotTitle = itemJson.get(titleKey).getAsString();
                    String hotUrl = itemJson.get(urlKey).getAsString();
                    hotList.add(new HotNewsDTO(typeKey, hotTitle, hotUrl));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取{}失败,异常:{}", typeKey, e.getMessage());
        }

    }


}
